﻿using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Net;
using System.Net.NetworkInformation;
using System.Windows.Forms;

namespace DeskDeviceInfo
{
    public partial class Form1 : Form
    {

        public Form1()
        {
            InitializeComponent();
            FormBorderStyle = FormBorderStyle.None;
            this.BackColor = Color.Black;
            try
            {
                //ShowNetworkInterfaceMessage();
                label2.Text = IpaddrConvert(ShowNetworkInterfaceMessage());// GetIPAddress());
                this.TransparencyKey = Color.Black;
                Rectangle rec = Screen.GetWorkingArea(this);
                int SW = rec.Width;
                Location = new Point(SW - Width, 50);
#if !DEBUG
                CreateStartup();
#endif    
            }
            catch (Exception)
            {

            }

        }
        #region 内存回收
        /// <summary>
        /// 释放内存
        /// </summary>
        public static void ClearMemory()
        {
            GC.Collect();
            GC.WaitForPendingFinalizers();

        }
        #endregion
        protected override CreateParams CreateParams
        {
            get
            {
                const int WS_EX_TOOLWINDOW = 0x80;
                CreateParams cp = base.CreateParams;
                cp.ExStyle |= WS_EX_TOOLWINDOW;      // 不显示在Alt-Tab
                return cp;
            }
        }

        /// <summary>
        /// 为当前程序创建后台启动文件到 开机启动文件夹
        /// </summary>
        static void CreateStartup()
        {
            try
            {
                RegistryKey RKey = Registry.LocalMachine.CreateSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run");

                object regobj = RKey.GetValue("DeskDeviceInfopro");
                if (regobj == null)
                {
                    string execPath = Application.ExecutablePath;

                    if (File.Exists(execPath) == true)
                    {
                        RKey.SetValue("DeskDeviceInfopro", execPath, RegistryValueKind.String);
                    }
                    execPath = null;
                }
                regobj = null;
                RKey.Close();
                RKey = null;
            }
            catch (Exception ex)
            {

            }

        }

        private static string GetIPAddress()
        {
            System.Net.IPAddress addr;    // 获得本机局域网IP地址   
            addr = new System.Net.IPAddress(Dns.GetHostByName(Dns.GetHostName()).AddressList[0].Address);
            string addrstr = addr.ToString();
            addr = null;
            return addrstr;
        }


        List<string> allmacaddr = new List<string>();
        /// <summary></summary>   
        /// 显示本机各网卡的详细信息
        /// <summary></summary>   
        public string ShowNetworkInterfaceMessage()
        {
            string addrestr = "";

            NetworkInterface[] fNetworkInterfaces = NetworkInterface.GetAllNetworkInterfaces();
            foreach (NetworkInterface adapter in fNetworkInterfaces)
            {
                #region " 网卡类型 "   

                string fRegistryKey = "SYSTEM\\CurrentControlSet\\Control\\Network\\{4D36E972-E325-11CE-BFC1-08002BE10318}\\" + adapter.Id + "\\Connection";
                Microsoft.Win32.RegistryKey rk = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(fRegistryKey, false);
                if (rk != null)
                {
                    // 区分 PnpInstanceID    
                    // 如果前面有 PCI 就是本机的真实网卡   
                    // MediaSubType 为 01 则是常见网卡，02为无线网卡。   
                    string fPnpInstanceID = rk.GetValue("PnpInstanceID", "").ToString();

                    if (fPnpInstanceID.Length > 3 &&
                        fPnpInstanceID.Substring(0, 3) == "PCI" &&
                        !fPnpInstanceID.Contains("Microsoft Loopback Adapter") &&
                        !fPnpInstanceID.Contains("Virtual Adapter") &&
                        !fPnpInstanceID.Contains("Virtual") &&
                        !fPnpInstanceID.Contains("VMware Virtual") &&
                        !fPnpInstanceID.Contains("VMware"))
                    {
                        IPInterfaceProperties iPInterfaceProperties = adapter.GetIPProperties();

                        UnicastIPAddressInformationCollection ipCollection = iPInterfaceProperties.UnicastAddresses;
                        foreach (UnicastIPAddressInformation ipadd in ipCollection)
                        {
                            //InterNetwork    IPV4地址      InterNetworkV6        IPV6地址
                            //Max            MAX 位址
                            if (ipadd.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
                                //判断是否为ipv4
                                //label1.Text = ipadd.Address.ToString();//获取ip
                                addrestr = string.IsNullOrEmpty(addrestr) ?
                                    ipadd.Address.ToString() :
                                    (addrestr + "\r\n" + ipadd.Address.ToString());
                        }

                    }
                }

                #endregion
            }
            return addrestr;
        }

        private string IpaddrConvert(string IpaddrStr)
        {
            string[] ipaddrstrlist = null;
            if (IpaddrStr.Contains(@"\r\n"))
            {
                ipaddrstrlist = IpaddrStr.Replace(@"\r\n", "。").Split('。');
            }
            else
            {
                ipaddrstrlist = new string[] { IpaddrStr };
            }

            string returnstr = "";
            for (int arrlen = 0; arrlen < ipaddrstrlist.Length; arrlen++)
            {
                string[] ipsplit = ipaddrstrlist[arrlen].Split('.');
                int shiweishu = int.Parse(ipsplit[2]) / 10;
                int geweishu = int.Parse(ipsplit[2]) % 10;
                if (shiweishu == 0)
                {
                    if (int.Parse(ipsplit[2]) == 0)
                    {
                        returnstr = "0";
                    }
                    else
                    {
                        byte[] array = new byte[1];
                        array[0] = (byte)(Convert.ToInt32(65 - 1 + int.Parse(ipsplit[2]))); //ASCII码强制转换二进制
                        returnstr = Convert.ToString(System.Text.Encoding.ASCII.GetString(array));
                        array = null;
                    }
                }
                else if (shiweishu >= 1)
                {
                    byte[] array = new byte[1];
                    array[0] = (byte)(Convert.ToInt32(65 - 1 + shiweishu)); //ASCII码强制转换二进制
                    returnstr = Convert.ToString(System.Text.Encoding.ASCII.GetString(array)) + geweishu;
                    array = null;
                }
                returnstr += "-" + ipsplit[3];

                shiweishu = geweishu = 0; 
                ipsplit = null;
            }

            ipaddrstrlist = null;
            IpaddrStr = null;
            return returnstr;
        }

        private const int WM_DISPLAYCHANGE = 0x007E;
        protected override void WndProc(ref Message m)
        {
            if (m.Msg == WM_DISPLAYCHANGE)
            {
                Rectangle rec = Screen.GetWorkingArea(this);
                int SW = rec.Width;
                Location = new Point(SW - Width, 50);
            }
            base.WndProc(ref m);
        }


    }
}
